package com.csp.mingyue.push.controller;

import cn.hutool.core.util.RandomUtil;
import com.csp.mingyue.common.core.constant.CacheConstants;
import com.csp.mingyue.common.core.constant.Constants;
import com.csp.mingyue.common.core.utils.SpringUtils;
import com.csp.mingyue.common.core.vo.R;
import com.csp.mingyue.common.redis.utils.RedisUtils;
import com.csp.mingyue.common.sms.core.SmsTemplate;
import com.csp.mingyue.common.sms.support.SmsProperties;
import com.csp.mingyue.common.sms.vo.SmsResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务
 *
 * @author Strive
 * @date 2023/8/24 14:59
 */
@Slf4j
@Tag(name = "短信服务模块")
@Validated
@RestController
@RequestMapping("sms")
@RequiredArgsConstructor
public class SmsController {

	private final SmsProperties smsProperties;

	/**
	 * 短信验证码
	 * @param phone 用户手机号
	 */
	@GetMapping("/code")
	@Operation(summary = "短信验证码", parameters = { @Parameter(name = "phone", description = "手机号", required = true) })
	public R<Void> smsCaptcha(@Valid @NotBlank(message = "手机号不能为空") String phone) {
		if (!smsProperties.getEnabled()) {
			return R.fail("当前系统没有开启短信功能！");
		}
		String key = CacheConstants.CAPTCHA_CODE_KEY + phone;
		String code = RandomUtil.randomNumbers(4);
		RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
		log.info("验证码短信「{}」发送至手机「{}」", code, phone);
		// 验证码模板 ID
		String templateId = "";
		Map<String, String> map = new HashMap<>(1);
		map.put("code", code);
		SmsTemplate smsTemplate = SpringUtils.getBean(SmsTemplate.class);
		SmsResult result = smsTemplate.send(phone, templateId, map);
		if (!result.getIsSuccess()) {
			log.error("验证码短信发送异常 => {}", result);
			return R.fail(result.getMessage());
		}
		return R.ok();
	}

}
